import { NextResponse } from 'next/server';
import { query } from '@/lib/database';
import { verifyPassword, generateToken } from '@/lib/auth';

export async function POST(request: Request) {
  try {
    const { username, password } = await request.json();

    // 查找用户
    const users = await query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    ) as any[];

    if (users.length === 0) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 400 }
      );
    }

    const user = users[0];

    // 验证密码
    const isValidPassword = await verifyPassword(password, user.password);
    if (!isValidPassword) {
      return NextResponse.json(
        { error: '密码错误' },
        { status: 400 }
      );
    }

    // 生成token
    const token = generateToken({
      userId: user.id,
      username: user.username
    });

    return NextResponse.json({
      message: '登录成功',
      token,
      user: { id: user.id, username: user.username, email: user.email }
    });
  } catch (error) {
    console.error('登录错误:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}